package ru.st.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;

import ru.st.selenium.model.Film;

public class InternalPage extends AnyPage {

	public InternalPage(PageManager pages) {
		super(pages);
	}

	public InternalPage ensurePageLoaded() {
		super.ensurePageLoaded();
		wait.until(presenceOfElementLocated(By.cssSelector("nav")));
		return this;
	}

	@FindBy(css = "nav a[href $= '?go=profile']")
	private WebElement userProfileLink;

	@FindBy(css = "nav a[href $= '?go=users']")
	private WebElement userManagementLink;

	@FindBy(css = "nav a[href $= '?logout']")
	private WebElement logoutLink;

	@FindBy(css = "div a[href='./?go=add']")
	private WebElement addFilm;

	@FindBy(xpath = "//div[@id='results']")
	private WebElement boxOfFilm;

	@FindBy(xpath = "//div[@class='searchbox']/input[@id='q']")
	private WebElement fieldOfSearch;

	@FindBy(xpath = "//div[@id='content']")
	private WebElement fieldLoading;

	public UserProfilePage clickUserProfilePage() {
		userProfileLink.click();
		return pages.userProfilePage;
	}

	public UserManagementPage clickUserManagementLink() {
		userManagementLink.click();
		return pages.userManagementPage;
	}

	public LoginPage clickLogoutLink() {
		logoutLink.click();
		wait.until(alertIsPresent()).accept();
		return pages.loginPage;
	}

	public AddNewFilmPage clickAddFilm() {
		addFilm.click();
		return pages.addNewFilmPage;

	}

	public EditFilmPage clickRndFilm(int n) {

		WebElement rndFilm = boxOfFilm.findElements(By.tagName("a")).get(n);
		rndFilm.findElement(By.cssSelector(".title")).click();

		return pages.editFilmPage;
	}

	public int numberOfFilms() {

		return boxOfFilm.findElements(By.tagName("a")).size();

	}

	public String resultOfSearchFilm(String name) throws InterruptedException {
		formForSearching(name);
		String titleOfFoundObject = null;
		try {
			titleOfFoundObject = boxOfFilm.findElement(
					By.cssSelector("div.title")).getText();
		} catch (Exception e) {
			titleOfFoundObject = boxOfFilm.findElement(
					By.cssSelector("div.content")).getText();
			System.out.println(titleOfFoundObject);
		}

		return titleOfFoundObject;

	}

	private void formForSearching(String name) throws InterruptedException {
		wait.until(ExpectedConditions.presenceOfElementLocated(By.id("q")));
		fieldOfSearch.clear();
		fieldOfSearch.sendKeys(name);
		fieldOfSearch.click();
		fieldOfSearch.sendKeys(Keys.RETURN);

		Thread.sleep(10000);
	}

}
